import { useState, useEffect } from 'react'
import { 
  Table, 
  Button, 
  Modal, 
  Form, 
  Input, 
  message, 
  Popconfirm, 
  Space, 
  Tag, 
  Upload, 
  Select,
  Card,
  DatePicker,
  InputNumber
} from 'antd'
import { 
  SearchOutlined, 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined,
  UploadOutlined,
  EyeOutlined
} from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import type { UploadProps } from 'antd/es/upload'
import type { UploadFile } from 'antd/es/upload/interface'
import dayjs from 'dayjs'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'

const { TextArea } = Input
const { Option } = Select

interface NewsType {
  id: string
  title: string
  content: string
  coverImage?: string
  category: string
  author: string
  status: 'draft' | 'published' | 'archived'
  publishDate?: string
  views: number
  createdAt: string
}

export default function NewsManagement() {
  const [newsList, setNewsList] = useState<NewsType[]>([])
  const [loading, setLoading] = useState(false)
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [currentNews, setCurrentNews] = useState<NewsType | null>(null)
  const [form] = Form.useForm()
  const [searchText, setSearchText] = useState('')
  const [fileList, setFileList] = useState<UploadFile[]>([])
  const [content, setContent] = useState('')

  // 模拟从API获取新闻数据
  useEffect(() => {
    fetchNews()
  }, [])

  const fetchNews = () => {
    setLoading(true)
    // 这里应该是API调用，我们使用模拟数据
    setTimeout(() => {
      const mockNews: NewsType[] = [
        {
          id: '1',
          title: '凯泽利科技新品发布会',
          content: '<p>凯泽利科技将于下月发布全新产品线...</p>',
          coverImage: 'https://example.com/news1.jpg',
          category: '企业新闻',
          author: '管理员',
          status: 'published',
          publishDate: '2023-06-01T10:00:00Z',
          views: 1024,
          createdAt: '2023-05-25T14:30:00Z'
        },
        {
          id: '2',
          title: '行业发展趋势分析',
          content: '<p>本文将分析当前行业的主要发展趋势...</p>',
          category: '行业资讯',
          author: '编辑',
          status: 'draft',
          views: 0,
          createdAt: '2023-06-05T09:15:00Z'
        },
        {
          id: '3',
          title: '2023年度技术峰会回顾',
          content: '<p>以下是本次技术峰会的主要内容和亮点...</p>',
          coverImage: 'https://example.com/news3.jpg',
          category: '活动报道',
          author: '记者',
          status: 'published',
          publishDate: '2023-06-10T15:30:00Z',
          views: 768,
          createdAt: '2023-06-08T11:20:00Z'
        }
      ]
      setNewsList(mockNews)
      setLoading(false)
    }, 500)
  }

  // 图片上传配置
  const uploadProps: UploadProps = {
    onRemove: file => {
      const index = fileList.indexOf(file)
      const newFileList = fileList.slice()
      newFileList.splice(index, 1)
      setFileList(newFileList)
    },
    beforeUpload: file => {
      setFileList([...fileList, file])
      return false
    },
    fileList,
    accept: 'image/*',
    listType: 'picture',
    maxCount: 1
  }

  // 过滤新闻数据
  const filteredNews = newsList.filter(news =>
    news.title.toLowerCase().includes(searchText.toLowerCase()) ||
    news.content.toLowerCase().includes(searchText.toLowerCase()) ||
    news.author.toLowerCase().includes(searchText.toLowerCase())
  )

  const handleAdd = () => {
    setCurrentNews(null)
    setContent('')
    setFileList([])
    form.resetFields()
    setIsModalOpen(true)
  }

  const handleEdit = (news: NewsType) => {
    setCurrentNews(news)
    setContent(news.content)
    setFileList(news.coverImage ? [{
      uid: '-1',
      name: 'coverImage',
      status: 'done',
      url: news.coverImage
    }] : [])
    form.setFieldsValue({
      ...news,
      publishDate: news.publishDate ? dayjs(news.publishDate) : null
    })
    setIsModalOpen(true)
  }

  const handleDelete = (id: string) => {
    // 这里应该是API调用
    setNewsList(newsList.filter(news => news.id !== id))
    message.success('新闻删除成功')
  }

  const handleStatusChange = (id: string, status: 'draft' | 'published' | 'archived') => {
    // 这里应该是API调用
    const updatedNews = newsList.map(news => {
      if (news.id === id) {
        return {
          ...news,
          status,
          publishDate: status === 'published' ? new Date().toISOString() : news.publishDate
        }
      }
      return news
    })
    setNewsList(updatedNews)
    message.success(`新闻已${status === 'published' ? '发布' : status === 'archived' ? '归档' : '保存为草稿'}`)
  }

  const handleSubmit = () => {
    form.validateFields().then(values => {
      const coverImage = fileList.length > 0 ? 
        (fileList[0].url || URL.createObjectURL(fileList[0] as any)) : 
        currentNews?.coverImage
      
      const newsData = {
        ...values,
        content,
        coverImage,
        publishDate: values.publishDate ? values.publishDate.toISOString() : null
      }

      if (currentNews) {
        // 更新新闻
        setNewsList(newsList.map(news => 
          news.id === currentNews.id ? { ...news, ...newsData } : news
        ))
        message.success('新闻更新成功')
      } else {
        // 添加新闻
        const newNews = { 
          ...newsData, 
          id: Date.now().toString(),
          author: '当前用户', // 实际应该获取当前用户
          views: 0,
          createdAt: new Date().toISOString()
        }
        setNewsList([...newsList, newNews])
        message.success('新闻添加成功')
      }
      setIsModalOpen(false)
    })
  }

  const getStatusTag = (status: string) => {
    switch (status) {
      case 'draft':
        return <Tag color="orange">草稿</Tag>
      case 'published':
        return <Tag color="green">已发布</Tag>
      case 'archived':
        return <Tag color="blue">已归档</Tag>
      default:
        return <Tag>未知</Tag>
    }
  }

  const columns: ColumnsType<NewsType> = [
    {
      title: '新闻标题',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      render: (text, record) => (
        <a onClick={() => handleEdit(record)}>{text}</a>
      )
    },
    {
      title: '封面图',
      dataIndex: 'coverImage',
      key: 'coverImage',
      width: 100,
      render: (image) => (
        image ? <img src={image} alt="封面" style={{ width: 60, height: 40, objectFit: 'cover' }} /> : '-'
      )
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 120
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: status => getStatusTag(status)
    },
    {
      title: '发布时间',
      dataIndex: 'publishDate',
      key: 'publishDate',
      width: 180,
      render: text => text ? dayjs(text).format('YYYY-MM-DD HH:mm') : '-'
    },
    {
      title: '浏览量',
      dataIndex: 'views',
      key: 'views',
      width: 100,
      render: views => <span>{views.toLocaleString()}</span>
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          {record.status !== 'published' && (
            <Button 
              type="link" 
              onClick={() => handleStatusChange(record.id, 'published')}
            >
              发布
            </Button>
          )}
          {record.status === 'published' && (
            <Button 
              type="link" 
              onClick={() => handleStatusChange(record.id, 'archived')}
            >
              归档
            </Button>
          )}
          <Popconfirm
            title="确定要删除此新闻吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <h2>新闻资讯管理</h2>
        <p>管理网站发布的新闻和资讯内容</p>
        
        <Space style={{ marginBottom: 16 }}>
          <Input
            placeholder="搜索新闻"
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={e => setSearchText(e.target.value)}
            style={{ width: 300 }}
          />
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            添加新闻
          </Button>
        </Space>
      </div>

      <Table
        columns={columns}
        dataSource={filteredNews}
        rowKey="id"
        loading={loading}
        bordered
        pagination={{ pageSize: 10 }}
        scroll={{ x: 1200 }}
      />

      <Modal
        title={currentNews ? '编辑新闻' : '添加新闻'}
        open={isModalOpen}
        onOk={handleSubmit}
        onCancel={() => setIsModalOpen(false)}
        width={800}
        style={{ top: 20 }}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="title"
            label="新闻标题"
            rules={[{ required: true, message: '请输入新闻标题' }]}
          >
            <Input placeholder="请输入新闻标题" />
          </Form.Item>

          <Form.Item
            name="category"
            label="新闻分类"
            rules={[{ required: true, message: '请选择新闻分类' }]}
          >
            <Select placeholder="请选择新闻分类">
              <Option value="企业新闻">企业新闻</Option>
              <Option value="行业资讯">行业资讯</Option>
              <Option value="活动报道">活动报道</Option>
              <Option value="产品动态">产品动态</Option>
              <Option value="技术分享">技术分享</Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="封面图片"
          >
            <Upload {...uploadProps}>
              <Button icon={<UploadOutlined />}>上传封面</Button>
            </Upload>
            <p style={{ color: '#999', marginTop: 8 }}>建议尺寸：800x450像素，大小不超过2MB</p>
          </Form.Item>

          <Form.Item
            name="publishDate"
            label="发布时间"
          >
            <DatePicker 
              showTime 
              style={{ width: '100%' }} 
              placeholder="选择发布时间（留空将立即发布）"
            />
          </Form.Item>

          <Form.Item
            label="新闻内容"
            required
          >
            <ReactQuill
              theme="snow"
              value={content}
              onChange={setContent}
              style={{ height: 300, marginBottom: 50 }}
              modules={{
                toolbar: [
                  [{ 'header': [1, 2, 3, false] }],
                  ['bold', 'italic', 'underline', 'strike'],
                  [{ 'color': [] }, { 'background': [] }],
                  [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                  ['link', 'image'],
                  ['clean']
                ]
              }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}